<template>
  <div style="height: 100%;">
    <div class="scan" @click="scanHandle" v-if="assetsFlag"/>
    <div class="columnBg">
      <van-form ref="form">

        <div class="imgBox">
          <!--          <div>请上传故障图片</div>-->
          <van-field name="uploader" class="picStyle">
            <template #input>
              <div class="picMain">
<!--                <van-uploader :accept="accept"-->
<!--                              :before-read="uploadBefore"-->
<!--                              :before-delete="onDel"-->
<!--                              v-model="fileList"-->
<!--                              :max-count="1"/>-->
                <uploadCom ref="uploadRef"
                           :maxNumber="1"
                           @uploadFileIds="uploadFileIds"
                           accept=".png,.jpg,.jpeg"
                           :defaultFiles="defaultFiles" />
              </div>
            </template>
          </van-field>
        </div>

        <van-field v-model="formData.shenqbm"
                   required
                   label="申请部门"
                   name="申请部门"
                   placeholder="请输入申请部门"
                   :rules="ruleForm.shenqbm"/>

        <van-field v-model="formData.lianxdh"
                   :required="false"
                   label="联系电话"
                   name="联系电话"
                   placeholder="请输入联系电话"
                   :rules="ruleForm.lianxdh"/>
      </van-form>
      <div class="followerBox">
        <h5 @click="isFold = !isFold;">
          物资报修申请清单（{{ listData.length }}）
          <p v-if=" isFold ">展开
            <van-icon name="arrow-down"/>
          </p>
          <p v-else>折叠
            <van-icon name="arrow-up"/>
          </p>
          <van-button size="mini" round type="info" icon="plus" @click=" handleAdd " />
        </h5>
        <div v-show=" !isFold " class="list">
          <div v-for="( val, ind ) in  listData " :key=ind class="list-item">
            <div class="right">
              <div class="iconClose">
                <van-icon name="close" size="18" color="#ee0a24" @click=" handleDelete(val, ind) "/>
              </div>
              <div>
                <label>物资大类：</label>
                <p>{{ val.wzdlName || "-" }}</p>
              </div>
              <div>
                <label>物资小类：</label>
                <p>{{ val.wzxlName || "-" }}</p>
              </div>
              <div>
                <label>品名：</label>
                <p>{{ val.PINM || "-" }}</p>
              </div>
              <div>
                <label>保管人：</label>
                <p>{{ val.BGRNAME || "-" }}</p>
              </div>
              <div>
                <label>故障描述：</label>
                <p></p>
                <van-field v-model="val.gzyy" placeholder="请输入故障描述"/>
              </div>
            </div>
            <!-- <van-button plain color="#ee0a24" @click="handleDelete(ind)">删除</van-button> -->
          </div>
          <van-empty v-if=" !listData.length " class="custom-image"
                     :image=" require('../../../../assets/images/empty.png') " description="暂无办公物资"/>
        </div>
      </div>
      <van-button class="defaultBtn" size="large" color="#4eb3e9" @click=" handleSave ">提交</van-button>
    </div>

    <fullscreenModal :modal=" fullscreenModal " :editType=" 'other' " label="选择物资" :showSubmit=" false "
                     :showSave=" false "
                     @handleClose=" fullscreenModal = false ">
      <article-form @close=" fullscreenModal = false " ref="articleForm" @restLsit="restLsit " @addList="addList"
                    @goBack=" fullscreenModal = false "/>
    </fullscreenModal>

  </div>
</template>

<script>
import {
  getDetailBySwid,
  queryBgwzxx,
  saveBgwzwxsq,
  saveGuzbx
} from "@/api/srvAssurance/assetLabel/assetLabel";
import {queryDic, uploadAttach} from '@/api/common';
import articleForm from './articleForm';
import {checkAssetsFlag} from "@api/srvAssurance/convApp";

export default {
  components: {
    articleForm,
  },
  data() {
    return {
      accept: '.png,.jpg,.jpeg',
      defaultFiles: [],
      maxSize: 51200, // 文件最大：50M
      fileList: [],
      loading: false,

      assetsFlag: false,
      fullscreenModal: false,
      isFold: true,
      chooseWzList: [],
      formData: {
        id: '',
        shenqbm: '',            // 申请部门     必填
        file: '',               // 附件           不必填
        attachOssId: '',        // 不需要传
        lianxdh: '',            // 联系电话         不必填
        wuzid: '',              //  物资id          例:  '123123123,22222,3333'
        gzyy: '',               // 故障描述 必填      例:  'xxxxx,cccccc,vvvvvv'
        fileCodeArr: [],        // 附件code
      },
      ruleForm: {
        shenqbm: [
          {required: true, message: '请输入申请部门', trigger: 'blur'},
        ],
        lianxdh: [
          {required: false, message: '请输入联系电话', trigger: 'blur'},
        ],
      },
      listData: [],

      dlList: [], // 物资大类
      wzxlList: [], // 物资小类
    };
  },
  created() {
    this.getDicData();
  },
  methods: {
    // 附件上传
    uploadFileIds (arr) {
      this.formData.fileCodeArr = arr;
    },

    // 附件上传之前（进行附件大小、类型验证）
    uploadBefore(file) {
      let format = this.accept.replace(/\./g, '').split(",");
      if ((file.size / 1000) > this.maxSize) {
        this.$Notify({type: "warning", message: `文件大小不能超过${(this.maxSize / 1024)}M!`});
        return false;
      } else if (!format.includes((file.name.split('.')[file.name.split('.').length - 1]).toLowerCase())) {
        this.$Notify({type: "warning", message: '文件格式有误,请上传' + format.join('、') + '格式文件！'});
        return false;
      }
      uploadAttach(file).then(res => {
        if (res.code === 1000 && res.data) {
          this.fileList.push({url: res.data.url});
          this.formData.fileCodeArr.push(res.data.fileCode);
        }
      })
    },
    // 文件删除前的
    onDel(file, obj) {
      this.fileList.splice(obj.index, 1);
      this.formData.fileCodeArr.splice(obj.index, 1);
    },

    restLsit(val) {
      this.listData = val
    },
    addList(val) {
      this.listData = val
    },

    // 提交
    handleSave() {
      let isBoo = false;
      this.$refs.form.validate().then(async () => {
        if (this.listData.length < 1) {
          this.$Notify({type: 'warning', message: "办公物资报修申请单不能为空！"});
          isBoo = true;
        }
        this.listData.forEach(item => {
          if (item.gzyy == null) {
            this.$Notify({type: 'warning', message: "请输入故障描述!"});
            isBoo = true;
          }
        })
        if (isBoo) {
          return
        }
        let saveParam = {};
        saveParam.id = this.formData.id;
        saveParam.shenqbm = this.formData.shenqbm;
        saveParam.attachOssId = this.formData.attachOssId;
        saveParam.lianxdh = this.formData.lianxdh;
        saveParam.file = this.formData.fileCodeArr[0];

        let wuziId = '';
        let gzyy = '';
        this.listData.forEach(item => {
          wuziId = wuziId + item.ID + ',';
          gzyy = gzyy + item.gzyy + ',';
        })
        saveParam.wuzid = wuziId;
        saveParam.gzyy = gzyy;
        saveParam.type = 'add';
        saveParam.shebType = '04';
        saveGuzbx(saveParam).then(res => {
          this.$Notify({type: "success", message: "保存成功！"});
          this.$emit("close");
          this.$emit("refresh");
        })
      })
    },

    // 添加
    handleAdd(e) {
      this.fullscreenModal = true;
      this.$refs.articleForm.removeLsit = this.listData;
      this.$refs.articleForm.onRefresh();
    },
    // 删除
    handleDelete(index) {
      this.listData.splice(index, 1);
    },
    // 重置
    resetForm() {
      this.isFold = true;
      this.formData = {
        id: '',
        shenqbm: '',            // 申请部门     必填
        file: '',               // 附件           不必填
        attachOssId: '',        // 不需要传
        lianxdh: '',            // 联系电话         不必填
        wuzid: '',              //  物资id          例:  '123123123,22222,3333'
        gzyy: '',               // 故障描述 必填      例:  'xxxxx,cccccc,vvvvvv'
        fileCodeArr: [],        // 附件code
      };

      // this.assetsFlag = false;
      // this.listData = [];
      this.fullscreenModal = false;
      this.listData = [];
      this.fileList = [];
      setTimeout(() => {
        this.$refs.form.resetValidation();
      });
    },


    scanHandle() {
      let _this = this;
      wx.scanQRCode({
        desc: "scanQRCode desc",
        needResult: 1, // 默认为0，扫描结果由i国网处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: async function (res) {
          if (res.resultStr) {
            let queryParam = {};
            queryParam.swid = res.resultStr;
            let resData = await getDetailBySwid(queryParam);
            if (resData.status == 0) {
              let item = resData.data[0];
              if (item.shebType == "04") {
                let queryParam = {};
                queryParam.pinm = res.resultStr;
                queryParam.statusBf = '03';
                queryParam.wxsqqc = true;
                queryParam.searchType = 'simple';
                queryParam.page = 1;
                queryParam.rows = 20;
                queryBgwzxx(queryParam).then((res) => {
                  if (res.data.length > 0) {
                    let arr = res.data;
                    let e = arr[0];
                    _this.translate(e);
                    let param = {
                      ID: e.ID,
                      PINM: e.PINM,
                      WUZDL: e.WZDL,
                      WUZXL: e.WZXL,
                      BAOGR: e.BAOGR,
                      BGRNAME: e.BAOGRNAME,
                      wzdlName: e.wzdlName,
                      wzxlName: e.wzxlName,
                    }
                    // 判断 this.listData是否已经有了，根据ID判断
                    let isBoo = false;
                    _this.listData.forEach(item => {
                      if (item.ID == param.ID) {
                        isBoo = true;
                        return;
                      }
                    })
                    if (isBoo) {
                      _this.$Notify({type: 'warning', message: "该办公物资已经添加！"});
                    } else {
                      _this.listData.push(param);
                      console.log("this.listData", _this.listData)
                    }
                  }
                })
              } else {
                this.$Notify({type: 'warning', message: "请扫描办公物资二维码！"});
              }
            }
          }
        },
        error: function (res) {
          if (res.errMsg.indexOf("function_not_exist") > 0) {
            alert("版本过低请升级");
          }
        },
      });
    },

    translate(item) {
      this.dlList.some(val => {
        if (val.codeValue === item.WZDL) {
          this.$set(item, 'wzdlName', val.valueAlias);
          return true
        }
      })
      this.wzxlList.some(val => {
        if (val.codeValue === item.WZXL) {
          this.$set(item, 'wzxlName', val.valueAlias);
          return true
        }
      })
    },

    async queryBgwzEquipment(swid) {
      let queryParam = {};
      queryParam.pinm = '';
      queryParam.wzdl = '';
      queryParam.statusBf = '03';
      queryParam.wxsqqc = true;
      queryParam.searchType = 'simple';
      queryParam.page = 1;
      queryParam.rows = 20;
      queryBgwzxx(queryParam).then((res) => {
        this.loading = false;
        if (res.data.length > 0) {
          let arr = res.data;
          arr.map(item => {
            this.$set(item, 'checked', false)
          })
          this.listData = arr;
          // this.listData = [...this.listData, ...res.data];
          this.translate();
          this.decideLsit();
          if (this.listData.length >= res.totalCount) {
            this.finished = true;
          }
        } else {
          this.finished = true;
        }
      }).catch(() => {
        this.loading = false;
        this.finished = true;
      });
    },

    getDicData() {
      //大类
      queryDic('RA_WORK_FACILITYBIG_CODE').then(res => {
        if (res.code == 1000) {
          this.dlList = res.data
        }
      })
      //小类
      queryDic('RA_WORK_FACILITYSMALL_CODE').then(res => {
        if (res.code == 1000) {
          this.wzxlList = res.data
        }
      })
      checkAssetsFlag().then(res => {
        if (res.code === 1000 && res.data) {
          this.assetsFlag = res.data;
        }
      })
    }
  },
};
</script>

<style scoped lang="less">
.columnFlex {
  overflow: auto;
  background: #eee;
}

.van-form {
  background: #fff;

  .photoRow {
    display: flex;
    align-items: center;
    padding: 8px 15px 0;
    box-sizing: border-box;
    justify-content: space-between;
    position: relative;

    .left {
      line-height: 25px;

      p:nth-of-type(2) {
        color: #999;
        font-size: 12px;
      }
    }
  }

  .photoRow::after {
    position: absolute;
    box-sizing: border-box;
    content: " ";
    pointer-events: none;
    right: 0.42667rem;
    bottom: 0;
    left: 0.42667rem;
    border-bottom: 0.02667rem solid #ebedf0;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
  }

  /deep/ .van-field__button a {
    color: #4eb3e9;
    font-size: 13px;
  }

  .van-tag {
    margin-right: 10px;
    line-height: 22px;
    padding: 0 8px;
  }
}

h5 {
  background: #f1f1f2;
  font-size: 13px;
  line-height: 42px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  font-weight: normal;
  color: #666;
  position: relative;

  /deep/ .van-button--mini {
    padding: 0;
    width: 18px;
    height: 18px;
  }

  p {
    position: absolute;
    right: 45px;
  }
}

.followerBox {
  background: #fff;
  margin-top: 5px;

  h5 {
    background: #fff;
  }

  /deep/ .van-empty {
    padding: 20px 0;

    .van-empty__image {
      width: 50px;
      height: 50px;
    }
  }

  .list-item {
    display: flex;
    padding: 10px;
    box-sizing: border-box;
    align-items: center;
    border-bottom: 1px solid #eee;

    img {
      width: 60px;
      height: 60px;
      margin-right: 10px;
    }

    .right {
      flex: 1;
      overflow: hidden;

      div {
        display: flex;
        line-height: 22px;
        align-items: center;
        font-size: 12px;

        label {
          width: 105px;
          color: #999;
        }

        p {
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .iconClose {
        float: right;
      }
    }

    .van-button {
      height: 25px;
      padding: 0 10px;
      font-size: 12px;
    }
  }
}

.addFormBox {
  position: relative;

  p {
    text-align: center;
    line-height: 45px;
    font-size: 14px;
    margin-bottom: 5px;
    border-bottom: 1px solid #eee;
    color: #666;
  }

  & > div {
    padding: 0 10px;
    box-sizing: border-box;
  }

  .van-icon {
    position: absolute;
    right: 10px;
    top: 10px;
  }
}

.van-button--large {
  height: 40px;
  line-height: 40px;
  width: 95%;
  margin: 10px auto;
}

.van-dialog {
  /deep/ .van-dialog__header {
    padding: 10px 0;
  }

  .centerListBox {
    height: 180px;
    padding: 0 15px;
    line-height: 32px;
    font-size: 14px;
    overflow: auto;
    box-sizing: border-box;
    margin-bottom: 10px;

    li {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      position: relative;
      padding-right: 30px;
      box-sizing: border-box;

      .van-icon {
        position: absolute;
        font-size: 18px;
        top: 5px;
        right: 0;
        color: #4eb3e9;
      }
    }
  }
}


.imgBox {

  .picStyle {

    .picMain {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.scan {
  background-image: url('../../../../assets/images/nx/saoyisao-black.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  width: 26px;
  height: 26px;
  margin-top: -37px;
  margin-left: 88%;
  position: absolute;
  z-index: 9999;
  color: rgb(51, 51, 51);
}

</style>
